package com.usian.third.utils;

import com.alibaba.fastjson.JSON;
import com.usian.common.third.UserCheckDto;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;



/**
 * 这是三要素验证
 */

public class VerifyReaIName {

    //    前后端交互的时候调用实体类对象

    /**
     *
     * @param idcard  身份证号
     * @param mobile   电话号
     * @param name      姓名
     * @return  验证结果
     * @throws IOException
     */

    public Map checkUser(String idcard, String mobile, String name) throws IOException {
        String url = "https://mobile3elements.shumaidata.com/mobile/verify_real_name";
        String appCode = "c9c658d2010c4874b882a22d3f3cce20";

        Map<String,String> params = new HashMap<>();
        params.put("idcard",idcard);//410926199906080431
        params.put("mobile",mobile);//19538431071
        params.put("name",name);//张明伟
        String result =  postForm(appCode,url,params);
        UserCheckDto userCheckDto = JSON.parseObject(result,UserCheckDto.class);

        Map<String,String> map = new HashMap();


        if (!userCheckDto.getCode().equals("0")){

            map.put("code",userCheckDto.getCode());
            map.put("msg",userCheckDto.getMessage());
            return map;

        }else {
            map.put("code",userCheckDto.getCode());
            map.put("msg",userCheckDto.getResult().getRes());
            return map;
        }




    }

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     *  <dependency>
     *     <groupId>com.squareup.okhttp3</groupId>
     *     <artifactId>okhttp</artifactId>
     *     <version>3.13.1</version>
     *  </dependency>
     */
    public static String postForm(String appCode, String url, Map<String,String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while(it.hasNext()){
            String key = it.next();
            formbuilder.add(key,params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization","APPCODE "+appCode).post(body).build();
        Response response = client.newCall(request).execute();
//        System.out.println("返回状态码"+response.code()+",message:"+response.message());
        String result =  response.body().string();
        return result;
    }
}
